package pers.cz.jefconfig.jmx;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import pers.cz.jefconfig.log.LogUtils;

import javax.management.JMException;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.lang.management.ManagementFactory;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * @program: JefConfig
 * @description: jmx注册类
 * @author: Cheng Zhi
 * @create: 2024-09-16 11:51
 **/
public class JefMonitorRegister {

    public static boolean isJmxEnable(){
        return !"false".equals(System.getProperty("enable.jmx"));
    }

    public static void registeJefDefault() {
        if(isJmxEnable() && System.getProperty("jef.jmx.registed")==null){
            JefConfigMonitor mm = JefConfigMonitor.getInstance();
            registe(null,mm);

        }
    }

    public static synchronized void registe(String path,Object mxBean){
        System.setProperty("jef.jmx.registed","true");
        try{
            List<MBeanServer> servers = MBeanServerFactory.findMBeanServer(null);
            MBeanServer s;
            if (servers.isEmpty()) {
                s = ManagementFactory.getPlatformMBeanServer();
            } else {
                s = servers.get(0);
            }
            String clsName=mxBean.getClass().getSimpleName();
            String name=path==null?clsName+":name=default":path+",objectname="+clsName;
            ObjectName objName = new ObjectName(name);
            s.registerMBean(mxBean, objName);
            try{
                // startWebServer(); // web页面未完成...
			}catch(Exception e){

            }
        }catch(Throwable t){
            t.printStackTrace();
        }
    }

    public static void unregiste(String path,Object mxBean){
        try{
            List<MBeanServer> servers = MBeanServerFactory.findMBeanServer(null);
            MBeanServer s;
            if (servers.isEmpty()) {
                s = ManagementFactory.getPlatformMBeanServer();
            } else {
                s = servers.get(0);
            }
            if(mxBean==null){
                return;
            }
            String clsName=mxBean.getClass().getSimpleName();
            String name=path==null?clsName+":name=default":path+",objectname="+clsName;
            ObjectName objName = new ObjectName(name);
            s.unregisterMBean(objName);
        }catch(Throwable t){
            LogUtils.error("MBean Regist error!", t);
        }
    }

    private static void startWebServer() throws IOException {
        HttpServer server = HttpServer.create(new java.net.InetSocketAddress(8080), 0);
        server.createContext("/jmx", new JmxHandler());
        server.setExecutor(null); // creates a default executor
        server.start();
    }
    static class JmxHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            String response = "<html><h1>JMX MBeans</h1><ul>";
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            try {
                for (ObjectName name : mbs.queryNames(null, null)) {
                    response += "<li>" + name.getCanonicalName() + "</li>";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            response += "</ul></html>";
            exchange.sendResponseHeaders(200, response.length());
            OutputStream os = exchange.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
    }

}
